package logic

import (
	"12.10zy/model/mysql"
	"12.10zy/model/redis"
	"context"
	"fmt"

	"12.10zy/userrpc/internal/svc"
	"12.10zy/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *userrpc.LoginRequest) (*userrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	get := redis.Rdb.Get("sendSmslogin" + in.Phone)
	if get.Val() != in.SendSmsCode {
		return nil, fmt.Errorf("验证码错误")
	}
	users := mysql.User{
		Phone:    in.Phone,
		Password: in.Password,
	}
	mysql.DB.Debug().Where("phone = ?", in.Phone).Find(&users)
	if users.ID == 0 {
		mysql.DB.Debug().Create(&users)
		return nil, fmt.Errorf("用户未注册，已自动注册")
	}
	if users.Password != in.Password {
		return nil, fmt.Errorf("用户密码错误")
	}
	return &userrpc.LoginResponse{Id: int64(users.ID)}, nil
}
